<script>
import addIcon from "./assets/add.png"
import settings, { getBaseUrl } from "../../utils/settings"
import store from "../../store"
import { userActionType } from "@/store/modules/user"
import { getShowImage, showToast } from "@/utils"
import deleteIcon from "./assets/delete.svg"

export default {
  name: "index",
  props: {
    value: {
      type: String,
      default: "",
    },
    uploadUrl: {
      type: String,
      default: "resource/uploadFile",
    },
    //上传图片所带过去的额外的参数
    uploadParams: {
      type: Object,
      default: {},
    },
    uploadName: {
      type: String,
      default: "file",
    },
    //把上传成功后的数据转换成需要的格式
    afterUpload: {
      type: Function,
      default: () => {
        return (data) => {
          return data.data.url
        }
      },
    },
    allowDelete: {
      type: Boolean,
      default: false,
    },
    width: {
      type: String,
      default: "200rpx",
    },
    height: {
      type: String,
      default: "200rpx",
    },
		allowFileExtension: {
			type: Array,
			default: () => [
				"jpg",
				"jpeg",
				"png",
				"gif",
				"webp",
			]
		}
  },
  data() {
    return {
      addIcon,
      deleteIcon,
    }
  },
  methods: {
    getShowImage,
    uploadImage() {
			this.$emit('onChooseFile')
      uni.chooseImage({
        count: 1,
        success: (res) => {
					//检查文件类型
					const tempFilePaths = res.tempFilePaths
					const tempFilePath = tempFilePaths[0]
					const fileExtension = tempFilePath.split(".").pop()
					if (!this.allowFileExtension.includes(fileExtension)) {
						showToast.error("文件类型不支持")
						this.$emit("onError")
						return
					}
          uni.showLoading({
            title: "上传中",
            mask: true,
          })
          store.dispatch(userActionType.action.userInfo).then((userInfo) => {
            const tempFilePaths = res.tempFilePaths
            uni.uploadFile({
              url: getBaseUrl() + this.uploadUrl,
              filePath: tempFilePaths[0],
              name: this.uploadName,
              formData: this.uploadParams,
              header: {
                [settings.tokenKey]: userInfo.token,
              },
              success: (res) => {
                uni.hideLoading()
                const data = JSON.parse(res.data)
                if (data.code === 200) {
                  this.$emit("input", this.afterUpload(data))
                  this.$emit("change", data)
                } else {
									this.$emit("onError")
                  showToast.error(data.msg)
                }
              },
              fail: (err) => {
								this.$emit("onError")
                showToast.error(err.errMsg)
                uni.hideLoading()
              },
            })
          })
        },
      })
    },
    //删除图片
    handleDelete() {
      this.$emit("input", "")
      this.$emit("change", null)
    },
    //预览图片
    previewImage() {
      uni.previewImage({
        urls: [getShowImage(this.value)],
      })
    },
  },
  emits: ["input", "change", "onError","onChooseFile"],
}
</script>

<template>
  <view class="component" :style="{ width, height }">
    <view class="placeholder" v-if="!value" @click="uploadImage">
      <image class="icon" :src="addIcon"></image>
      <view class="text">上传图片</view>
    </view>
    <image
      class="image-container"
      v-else
      :src="getShowImage(value)"
      @click="
        () => {
          if (allowDelete) {
            previewImage()
          } else {
            uploadImage()
          }
        }
      "
    ></image>
    <view class="delete-icon-container" v-if="allowDelete && value">
      <image class="delete-icon" :src="deleteIcon" @click.stop="handleDelete"></image>
    </view>
  </view>
</template>

<style scoped lang="scss">
.component {
  width: 200rpx;
  height: 200rpx;
  position: relative;

  .delete-icon-container {
    position: absolute;
    top: -20rpx;
    right: -20rpx;
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    overflow: hidden;
    background: white;
    .delete-icon {
      width: 100%;
      height: 100%;
    }
  }

  .placeholder {
    background: #f2f2f2;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    height: 100%;

    > .icon {
      width: 60rpx;
      height: 60rpx;
    }

    > .text {
      margin-top: 10rpx;
      font-size: 28rpx;
      color: #999999;
    }
  }

  > .image-container {
    width: 100%;
    height: 100%;
  }
}
</style>
